from django.shortcuts import render,redirect
from django.http import HttpResponse,JsonResponse
from myadmin import models
from django.core.urlresolvers import reverse
# Create your views here.
def myhome_info(request):
    #获取当前点击的商品id
    gid = request.GET.get('gid')
    #获取当前商品信息
    ugoods = models.Goods.objects.get(id=gid)

    #返回到页面
    return render(request,'myhome/goodsinfo.html',{'ginfo':ugoods})

# 添加购物车
def addcar(request):
    try:
         # 接受商品的id 和数量 获取用的id
        info = request.GET.dict()
        # 获取商品的对象
        gobj = models.Goods.objects.get(id=info['gid'])
        # 获取用户对象
        uobj = models.Users.objects.get(id=request.session['userinfo']['uid'])

        # 判断 当前用户 有没有添加当前的这个商品
        flag = models.Car.objects.filter(uid=uobj.id).filter(gid=gobj.id)
        if flag.count():
            # 获取商品更新
            for i in flag:
                i.num+=int(info['num'])
                i.save()
        else:
            # 入库
            car = models.Car()
            car.num=int(info['num'])
            car.gid=gobj
            car.uid=uobj
            car.save()

        return JsonResponse({"msg":1,'info':'添加成功'})
    except :
        return JsonResponse({"msg":1,'info':'添加失败'})

# 购物车页面
def carpage(request):
    # 查询当前用户的购物车
    uid = request.session.get('userinfo')
    if not uid:
        return HttpResponse('<script>alert("没有登录");location.href="'+reverse('myhome_login')+'"</script>')
    # 查询用户
    user = models.Users.objects.get(id=uid['uid'])
    # 根据外键查询购物车里有多少商品
    cgoods = user.car_set.all()


    return render(request,'myhome/cart.html',{'cgoods':cgoods})

# 修改数量
def caredit(request):
    # 接受数量和cid
    cinfo = request.GET.dict()
    # 根据id查询商品
    cobj = models.Car.objects.get(id=cinfo['cid'])
    # 修改数量
    cobj.num=int(cinfo['num'])
    cobj.save()

    return JsonResponse({'error':1,'msg':'修改成功'})

#删除
def delcart(request): 
    uid = request.GET.get('uid')
    user = models.Car.objects.get(id=uid)
    user.delete()
    return redirect(reverse('myhome_carpage'))

def confirm(request):
    cart = request.GET.get('cid').split(',')

    #获取当前的商品信息
    cargoods= models.Car.objects.filter(id__in=cart)
    # 返回一级城市的数据
    citys = models.Citys.objects.filter(upid=0)

    # 当前用户的收货地址
    userobj = models.Users.objects.get(id=request.session['userinfo']['uid'])
    address = userobj.address_set.all()

    return render(request,'myhome/pay.html',{'cargoods':cargoods,'citys':citys,'address':address})
# 城际联动
def getcitys(request):
    # 接受upid
    upid = request.GET['upid']
    citys = models.Citys.objects.filter(upid=upid).values()
    return JsonResponse(list(citys),safe=False)
# 存地址
def saveaddress(request):
    # 接受
    addinfo = request.GET.dict()
    # 存数据
    address = models.Address()
    address.name=addinfo['name']
    address.phone=addinfo['phone']
    address.sheng=models.Citys.objects.get(id=addinfo['sheng']).name
    address.shi=models.Citys.objects.get(id=addinfo['shi']).name
    address.xian=models.Citys.objects.get(id=addinfo['xian']).name
    address.addinfo=addinfo['addinfo']
    address.uid = models.Users.objects.get(id=request.session['userinfo']['uid'])
    address.save()
    return JsonResponse({'error':0,'msg':'添加成功'})

#删除收货地址
def deldizhi(request):
    # cid = request.GET.get('cid')
    try:
        rid = request.GET.get('rid')
        ress = models.Address.objects.get(id=rid)
        ress.delete()
        return JsonResponse({'error':1,'msg':'删除成功！'})
    except:
        return JsonResponse({'error':0,'msg':'删除失败！'})
   

# 生成订单
def createorder(request):
    oinfo = request.POST.dict()
    print(oinfo)
    # 订单
    order = models.Order()
    order.uid = models.Users.objects.get(id = request.session['userinfo']['uid'])
    order.phone = models.Address.objects.get(id=oinfo['dizhi']).phone
    order.name = models.Address.objects.get(id=oinfo['dizhi']).name
    # 地址
    sheng = models.Address.objects.get(id=oinfo['dizhi']).sheng
    shi = models.Address.objects.get(id=oinfo['dizhi']).shi
    xian = models.Address.objects.get(id=oinfo['dizhi']).xian
    addinfo = models.Address.objects.get(id=oinfo['dizhi']).addinfo
    print(addinfo)
    order.addinfo = sheng+shi+xian+addinfo

    order.wl = int(oinfo['wuliu'])
    order.pay = int(oinfo['zhifu'])

    order.total=0
    order.save()

    
    total=0
    carts = models.Car.objects.filter(id__in=oinfo['car'].split(','))
    for i in carts:
        # 订单详情
        orderinfo = models.Orderinfo()
        orderinfo.orderid = order
        orderinfo.num = i.num
        orderinfo.price = i.gid.price
        orderinfo.gid = i.gid
        orderinfo.save()
        total += i.num*i.gid.price
        i.delete()

    order.total = total
    order.save()


    # 跳转到支付
    return HttpResponse('<script>location.href="'+reverse('myhome_order_pay')+'?orderid='+str(order.id)+'"</script>')


# 订单支付
def myhome_order_pay(request):
    # 接收订单号
    orderid = request.GET.get('orderid')
    # 获取订单对象
    order = models.Order.objects.get(id=orderid)
    print(orderid)
    # 获取支付对象
    alipay = Get_AliPay_Object()

    # 生成支付的url
    query_params = alipay.direct_pay(
        subject="魅族旗舰官网",  # 商品简单描述
        out_trade_no = orderid,# 用户购买的商品订单号
        total_amount = order.total,  # 交易金额(单位: 元 保留俩位小数)
    )
    print(query_params)
    # 支付宝网关地址（沙箱应用）
    pay_url = settings.ALIPAY_URL+"?{0}".format(query_params)  
    print(pay_url)
    # 页面重定向到支付页面
    return redirect(pay_url)




# 支付的回调函数
# 支付宝回调地址
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def myhome_pay_result(request):
    # 获取对象
    alipay = Get_AliPay_Object()
    if request.method == "POST":
        # 检测是否支付成功
        # 去请求体中获取所有返回的数据：状态/订单号
        from urllib.parse import parse_qs
        # name&age=123....
        body_str = request.body.decode('utf-8')
        post_data = parse_qs(body_str)

        post_dict = {}
        for k, v in post_data.items():
            post_dict[k] = v[0]

        sign = post_dict.pop('sign', None)
        status = alipay.verify(post_dict, sign)
        print('------------------开始------------------')
        print('POST验证', status)
        
        out_trade_no = post_dict['out_trade_no']

        # 修改订单状态
        models.Order.objects.filter(id=out_trade_no).update(status=1)
        print('------------------结束------------------')
        # 修改订单状态：获取订单号
        return HttpResponse('POST返回')
    else:
        params = request.GET.dict()
        sign = params.pop('sign', None)
        status = alipay.verify(params, sign)
        print('==================开始==================')
        print('GET验证', status)
        print('==================结束==================')
       
        # return HttpResponse('<script>alert("支付成功");支付完成</script>')
        return HttpResponse('<script>alert("支付成功");location.href="'+reverse('myhome_personal')+'"</script>')


from shop import settings
from utils.pay import AliPay

# AliPay 对象实例化
def Get_AliPay_Object():
    alipay = AliPay(
        appid=settings.ALIPAY_APPID,# APPID （沙箱应用）
        app_notify_url=settings.ALIPAY_NOTIFY_URL, # 回调通知地址
        return_url=settings.ALIPAY_NOTIFY_URL,# 支付完成后的跳转地址
        app_private_key_path=settings.APP_PRIVATE_KEY_PATH, # 应用私钥
        alipay_public_key_path=settings.ALIPAY_PUBLIC_KEY_PATH,  # 支付宝公钥
        debug=True,  # 默认False,
    )
    return alipay
